<script lang="ts" setup>
import { inject, ref } from 'vue'
import { showModalKey } from '@/keys'
import { ShowModal } from '@/keys'
import { useWebsiteStore } from '@/store/websites.ts'
import URLJS from 'url-js'

const showModalInject = inject<typeof ShowModal>(showModalKey)
const isShowModal = showModalInject.isShowModal

const cancel = () => {
  showModalInject.setShowModal(false)
}

const url = ref('https://www.baidu.com')
const isSumbit = ref<boolean>(false)
const websiteStore = useWebsiteStore()
const add = async () => {
  isSumbit.value = true

  const urlObj = URLJS(url.value)

  const result = websiteStore.isSave({
    id: '',
    screenshot: 'string',
    title: 'string',
    url: 'string',
    href: urlObj.href
  })

  if (!!result) {
    window.exposeApi.alert('此网站已经被收录！')
    isSumbit.value = false
  } else {
    let result = await window.exposeApi.sendUrlToMain(url.value)

    websiteStore.add({
      id: Math.random().toString(36).substring(7).split('').join('.'),
      ...result
    })

    cancel()
    isSumbit.value = false
    url.value = ''
  }

}
</script>

<template>
  <div class="dialog-wrap" v-if="isShowModal">
    <div class="content">
      <div class="input">
        <input v-model="url" type="text" :disabled="isSumbit" placeholder="请输入网址..." @keyup.enter="add">
      </div>
      <div class="btns">
        <button @click="add" :disabled="isSumbit">添加</button>
        <button @click="cancel" :disabled="isSumbit">取消</button>
      </div>
    </div>
  </div>
</template>

<style lang="stylus">
.dialog-wrap
  position absolute
  top 0
  left 0
  right 0
  bottom 0
  z-index 1000
  background rgba(0,0,0, 0.8)
  display flex
  justify-content center
  align-items center
  .content
    width 100%
    padding 0 20px
    input
      height 30px
      width 100%
      outline none
      margin-bottom 10px
      font-size 12px
    .btns
      button
        height 30px
        margin-right 10px
        font-size 12px
        padding 0 20px
</style>